import csv


def read_csv():
    with open("test_file/stock.csv", "r") as fp:
        readers = csv.reader(fp)
        next(readers)
        for text in readers:
            print(text[1], text[2])


def read_csv_as_dict():
    with open("test_file/stock.csv", "r") as fp:
        readers = csv.DictReader(fp)
        for text in readers:
            val = {
                "date": text["date"],
                "code": text["code"]
            }
            print(val)


headers = ["姓名", "年龄", "爱好"]

values = [
    ('jack', 18),
    ('summit', 26)
]


# 写入到csv中
def writer_csv():
    with open("test_file/name.csv", 'w', encoding="utf-8", newline="") as fp:
        writer = csv.writer(fp)
        writer.writerow(headers)
        writer.writerows(values)


def writer_dict_csv():
    name_dict = [
        {
            "姓名": 'jack',
            "年龄": 17
        },
        {
            "姓名": 'summit',
            "年龄": 26,
            "爱好": "躺"
        }
    ]
    # 如果headers头部没有字典中该字段的名字,则会跳过该字典
    # 如果少则没事
    with open("test_file/name_dict.csv", 'w', encoding="utf-8", newline="") as fp:
        writer = csv.DictWriter(fp, headers)
        writer.writeheader()
        writer.writerows(name_dict)


if __name__ == '__main__':
    # read_csv()
    # read_csv_as_dict()
    # writer_csv()
    writer_dict_csv()
